<template>
  <div class="container-image">
    <slider-captcha
        v-model="sliderX"
        :image-url="image"
        :slider-url="slider"
        :y="sliderY"
        :loading="loading"
        :success="success"
        :view-on-hover="viewOnHover"
        @complete="(...args)=>$emit('complete', ...args)"
        @refresh="refresh"
        @mouseenter="!slider && refresh()"
        ref="sliderCaptcha"
    />
  </div>
</template>

<script lang="ts">
import {defineComponent, ref} from "vue";
import axios from "axios";
import SliderCaptcha from "../SliderCaptcha";
import MySliderCaptchaResponse from "@/components/MySliderCapthca/MySliderCaptchaResponse";

export default defineComponent({
  name: "MySliderCaptcha",
  components: {SliderCaptcha},
  props: {
    //验证码地址
    url: {
      default: "/my-slider-captcha",
      type: String
    },
    //是否已经验证成功
    success: Boolean,
    //用户鼠标滑入后再加载
    lazy: Boolean,
    //是否在鼠标移入后再展示
    viewOnHover: Boolean,
  },
  emits: ["update:loading", "complete"],
  setup(props, context){
    const sliderX = ref(0);
    const sliderY = ref(0);
    const image = ref("");
    const slider = ref("");
    const loading = ref(false);
    const customAxios = axios.create();
    const sliderCaptcha = ref();

    const refresh = async () => {
      loading.value = true;
      context.emit("update:loading", true);
      try {
        const result = await customAxios.get<MySliderCaptchaResponse>(props.url);
        const mySlider = result.data;
        sliderY.value = mySlider.y;
        image.value = mySlider.image;
        slider.value = mySlider.slider;
        sliderCaptcha.value.reset();
      }catch (e) {
        console.error("加载验证码失败： url=" + props.url, e);
      }finally {
        loading.value = false;
        context.emit("update:loading", false);
      }
    }

    if(!props.lazy) refresh();

    return {
      sliderX,
      sliderY,
      image,
      slider,
      loading,
      refresh,
      sliderCaptcha
    }
  }
})
</script>

<style scoped>
</style>
